package com.wlyuan.open.remote.consumer;

import com.wlyuan.open.domain.PushBusinessType;
import com.wlyuan.open.domain.PushTask;
import com.wlyuan.open.domain.assembler.PushTaskAssembler;
import com.wlyuan.open.domain.repository.PushTaskRepository;
import com.wlyuan.open.domain.repository.PushTenantRepository;
import com.wlyuan.open.remote.converter.CarrierMessageConverter;
import com.wlyuan.open.vo.push.basic.CarrierDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

/**
 * @author
 * 承运商同意
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CarrierInviteAgreedConsumer {
    private final CarrierMessageConverter messageConverter = new CarrierMessageConverter();
    private final PushTenantRepository pushTenantRepository;
    private final PushTaskRepository pushTaskRepository;

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = "queue.open.pusher.basic.carrier.customer.relation.agreed"),
                    exchange = @Exchange(value = "exchange.topic.basic"), key = "CarrierCustomerRelationAgreed")
    })
    public void receiveCarrierCustomerRelationAgreed(String message) {
        logger.info("承运商发货方关系同意事件：{}", message);
        CarrierDetailVO carrierDetailVO = messageConverter.convert(message).getCarrier();
        if (carrierDetailVO != null) {
            //判断租户id 是否在对接表中，如果存在，则将数据保存
            Long tenantId = carrierDetailVO.getTenantId();
            var pushTenant = pushTenantRepository.ofTenantAndType(tenantId, PushBusinessType.CARRIER_AGREED);
            if(pushTenant!=null){
                PushTask pushTask = PushTaskAssembler.merge(carrierDetailVO,pushTenant);
                pushTaskRepository.save(pushTask);
            }
        }
    }
}
